/**
 * 
 */
package com.newture.lxz.mail;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.template.expr.ast.Map;
import com.newture.lxz.db.mapper.LdMailMapper;
import com.newture.lxz.db.model.LdGoods;
import com.newture.lxz.db.model.LdGoodsExample;
import com.newture.lxz.db.model.LdMail;
import com.newture.lxz.db.model.LdMailExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * @author xiao.hu
 *
 */
public class Mail {

	@Resource
	LdMailMapper ldMailMapper;


	private MailConfig mailConfig = null;
	
	public Mail(MailConfig mailConfig) {
		this.mailConfig = mailConfig;
	}

	/**
	 * 发送邮件
	 * @throws Exception
	 */
	public void send(File attachment) throws Exception {
		// 1、连接邮件服务器的参数配置
		Properties props = new Properties();
		// 设置用户的认证方式
		props.setProperty("mail.smtp.auth", "true");
		// 设置传输协议
		props.setProperty("mail.transport.protocol", "smtp");
		// 设置发件人的SMTP服务器地址
		props.setProperty("mail.smtp.host", mailConfig.smtpHost);
		
		props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.smtp.socketFactory.port", "465");
		props.setProperty("mail.smtp.port", "465");
		props.put("mail.smtp.ssl.enable", true);
		
		// 2、创建定义整个应用程序所需的环境信息的 Session 对象
		Session session = Session.getInstance(props);
		// 设置调试信息在控制台打印出来
		session.setDebug(true);
		// 3、创建邮件的实例对象
		Message msg = getMimeMessage(session, attachment);
		// 4、根据session对象获取邮件传输对象Transport
		Transport transport = session.getTransport();
		// 设置发件人的账户名和密码
		transport.connect(mailConfig.senderAccount, mailConfig.senderPassword);
		// 发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人,
		// 抄送人, 密送人
		transport.sendMessage(msg, msg.getAllRecipients());

		// 如果只想发送给指定的人，可以如下写法
		// transport.sendMessage(msg, new Address[]{new
		// InternetAddress("xxx@qq.com")});

		// 5、关闭邮件连接
		transport.close();
	}

	/**
	 * 获得创建一封邮件的实例对象
	 *
	 */
	public MimeMessage getMimeMessage(Session session, File zipPath) throws Exception {
		// 创建一封邮件的实例对象
		MimeMessage msg = new MimeMessage(session);
		// 设置发件人地址
		msg.setFrom(new InternetAddress(mailConfig.senderAddress));
		/**
		 * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行 MimeMessage.RecipientType.TO:发送
		 * MimeMessage.RecipientType.CC：抄送 MimeMessage.RecipientType.BCC：密送
		 */
		msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(mailConfig.recipientAddress));
		// 设置邮件主题
		msg.setSubject(mailConfig.subject, "UTF-8");
		// 设置邮件正文
		msg.setContent(mailConfig.content, "text/html;charset=UTF-8");
		// 设置邮件的发送时间,默认立即发送
		msg.setSentDate(new Date());
		
		if(zipPath != null) {
			//添加zip附件
			MimeBodyPart attachment = new MimeBodyPart();
			//根据附件文件创建文件数据源
	        final DataSource ds = new FileDataSource(zipPath);
	        attachment.setDataHandler(new DataHandler(ds));
	        //为附件设置文件名
	        attachment.setFileName(ds.getName());
	        
	        final Multipart multipart = new MimeMultipart();
	        multipart.addBodyPart(attachment);

	        // 发送完整消息
	        msg.setContent(multipart);
		}
		
		return msg;
	}
	
	/**
	 * 测试
	 *formData:{
	 *    邮箱地址
	 *
	 *}
	 */
//	@PostMapping("/SendMail")
//	@RequestParam(name = "formData", required = false) String formData
	public void SendMail(@RequestParam(name = "formData", required = false) String formData) throws Exception {

		MailConfig mailConfig = new MailConfig();
		mailConfig.smtpHost = "smtp.163.com";
		mailConfig.senderAddress = "roypierre@163.com";
		mailConfig.recipientAddress = "2537306526@qq.com";
		mailConfig.senderAccount = "roypierre@163.com";
		mailConfig.senderPassword = "lawdoc20190816";
		mailConfig.subject = "邮件主题";
		mailConfig.content = "简单的纯文本邮件！";
		
		File testZip = new File("/Users/zxr/Desktop/Z/GraPractice/民事诉讼常用文件示例/（0423）52法定代表人身份证明书（申请执行人L）.docx");
		Mail mail = new Mail(mailConfig);
		mail.send(testZip);
	}
}
